//
//  CashView.m
//  location
//
//  Created by Dongxiang Xu on 2025/10/27.
//

#import "CashView.h"
#import "WXApi.h"
#import <AlipaySDK/AlipaySDK.h>
#import <StoreKit/StoreKit.h>

@interface CashView ()<SKProductsRequestDelegate,SKPaymentTransactionObserver>

@property (nonatomic,strong) UIView *infoView;
@property (nonatomic,assign) NSInteger sel;


@end

@implementation CashView

- (instancetype)initWithFrame:(CGRect)frame
                     CashInfo:(NSArray *)cashInfo
                    GroupInfo:(NSDictionary *)groupInfo
{
    self = [super initWithFrame:frame];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(PaySuccess) name:Noti_Pay_Success object:nil];
        [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
        
        self.layer.masksToBounds = YES;
        
        NSMutableArray *cashArray = [NSMutableArray array];
        for (NSDictionary *dic in cashInfo) {
            NSMutableDictionary *info = [NSMutableDictionary dictionaryWithDictionary:dic];
            if ([dic[@"name"] containsString:@"黄金"] && [dic[@"name"] containsString:@"年"]) {
                [info setValue:@"Gold_Year" forKey:@"productId"];
            }else if ([dic[@"name"] containsString:@"黄金"] && [dic[@"name"] containsString:@"季"]){
                [info setValue:@"Gold_Quarter" forKey:@"productId"];
            }else if ([dic[@"name"] containsString:@"黄金"] && [dic[@"name"] containsString:@"月"]){
                [info setValue:@"Gold_Month" forKey:@"productId"];
            }else if ([dic[@"name"] containsString:@"白银"] && [dic[@"name"] containsString:@"年"]){
                [info setValue:@"Silver_Year" forKey:@"productId"];
            }else if ([dic[@"name"] containsString:@"白银"] && [dic[@"name"] containsString:@"季"]){
                [info setValue:@"Silver_Quarter" forKey:@"productId"];
            }else if ([dic[@"name"] containsString:@"白银"] && [dic[@"name"] containsString:@"月"]){
                [info setValue:@"Silver_Month" forKey:@"productId"];
            }else if ([dic[@"name"] containsString:@"亲密"] && [dic[@"name"] containsString:@"年"]){
                [info setValue:@"Qm_Year" forKey:@"productId"];
            }else if ([dic[@"name"] containsString:@"亲密"] && [dic[@"name"] containsString:@"季"]){
                [info setValue:@"Qm_Quarter" forKey:@"productId"];
            }else if ([dic[@"name"] containsString:@"亲密"] && [dic[@"name"] containsString:@"月"]){
                [info setValue:@"Qm_Month" forKey:@"productId"];
            }
            [cashArray addObject:info];
        }
        
        _infoView = [[UIView alloc] initWithFrame:CGRectMake(12, SCREEN_HEIGHT, SCREEN_WIDTH-24, 425)];
        _infoView.backgroundColor = RealWhiteColor;
        _infoView.layer.masksToBounds = YES;
        [_infoView.layer setCornerRadius:40];
        [self addSubview:_infoView];
        
        UIButton *close = [[UIButton alloc] initWithFrame:CGRectMake(_infoView.width-46, 16, 30, 30)];
        [close setImage:[UIImage imageNamed:@"map_close"] forState:UIControlStateNormal];
        [_infoView addSubview:close];
        [[close rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [self close];
        }];
        
        UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake((_infoView.width-110)/2, 40, 28, 28)];
        img.image = [UIImage imageNamed:[NSString stringWithFormat:@"member_%@",cashArray.firstObject[@"type"]]];
        [_infoView addSubview:img];
        
        UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(img.maxX, 40, 84, 28)];
        if ([cashArray.firstObject[@"name"] containsString:@"-"]) {
            NSRange range = [cashArray.firstObject[@"name"] rangeOfString:@"-"];
            if (range.location != NSNotFound) {
                title.text = [NSString stringWithFormat:@"%@",[cashArray.firstObject[@"name"] substringToIndex:range.location]];
            }else{
                title.text = [NSString stringWithFormat:@"%@",cashArray.firstObject[@"name"]];
            }
        }else{
            title.text = [NSString stringWithFormat:@"%@",cashArray.firstObject[@"name"]];
        }
        title.textColor = RealBlackColor;
        title.font = MEDIUM_FONT(20);
        [_infoView addSubview:title];
        
        UILabel *subTitle = [[UILabel alloc] initWithFrame:CGRectMake(12, title.maxY+6, _infoView.width-24, 24)];
        subTitle.textAlignment = NSTextAlignmentCenter;
        subTitle.textColor = GraryLightColor;
        subTitle.font = DEFAULT_FONT(14);
        NSString *string = [NSString stringWithFormat:@"为 %@ %@",groupInfo[@"name"],([groupInfo[@"membership"] isKindOfClass:[NSDictionary class]]?@"续费":@"开通")];
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:string];
        [str addAttribute:NSFontAttributeName value:REAL_MEDIUM_FONT(14) range:NSMakeRange(2, [groupInfo[@"name"] length])];
        subTitle.attributedText = str;
        [_infoView addSubview:subTitle];
        
        for (int i = 0; i < cashArray.count; i++) {
            NSDictionary *dic = cashArray[i];
            
            UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(20, subTitle.maxY+28+i*49, _infoView.width-40, 21)];
            button.tag = 100+i;
            [_infoView addSubview:button];
            
            UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 2, 16, 16)];
            img.tag = 50+i;
            if (i==_sel) {
                img.image = [UIImage imageNamed:@"cash_sel"];
            }else{
                img.image = [UIImage imageNamed:@"cash_nor"];
            }
            [button addSubview:img];
            
            UILabel *name = [[UILabel alloc] initWithFrame:CGRectMake(img.maxX+9, 0, 62, button.height)];
            name.textColor = GraryHeavyLightColor;
            name.font = REAL_MEDIUM_FONT(15);
            if ([dic[@"name"] containsString:@"-"]) {
                NSRange range = [dic[@"name"] rangeOfString:@"-"];
                if (range.location != NSNotFound) {
                    name.text = [NSString stringWithFormat:@"%@",[dic[@"name"] substringFromIndex:range.location+range.length]];
                }else{
                    name.text = [NSString stringWithFormat:@"%@",dic[@"name"]];
                }
            }else{
                name.text = [NSString stringWithFormat:@"%@",dic[@"name"]];
            }
            [button addSubview:name];
            
            UILabel *price = [[UILabel alloc] initWithFrame:CGRectMake(button.width-47, 0, 47, button.height)];
            price.textColor = RealBlackColor;
            price.font = MEDIUM_FONT(15);
            price.text = [NSString stringWithFormat:@"%@元",dic[@"price"]];
            [price sizeToFit];
            [price setFrame:CGRectMake(button.width-price.width, 0, price.width, button.height)];
            [button addSubview:price];
            
            if ([dic[@"oriPrice"] integerValue]> [dic[@"price"] integerValue]) {
                UIImageView *sale = [[UIImageView alloc] initWithFrame:CGRectMake(price.x-49, (button.height-19)/2, 45, 19)];
                sale.image = [UIImage imageNamed:@"sale_cash"];
                [button addSubview:sale];
                
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(3, 0, 35, sale.height)];
                label.textColor = RealWhiteColor;
                label.textAlignment = NSTextAlignmentCenter;
                label.text = [NSString stringWithFormat:@"-%d%%",(int)((([dic[@"oriPrice"] floatValue]-[dic[@"price"] floatValue])/[dic[@"oriPrice"] floatValue])*100)];
                label.font = RUBIK_ITALIC_FONT(13);
                
                [sale addSubview:label];
            }
            
            [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                for (int j = 0 ; j < cashArray.count; j ++) {
                    ((UIImageView *)[self viewWithTag:50+j]).image = [UIImage imageNamed:@"cash_nor"];
                }
                img.image = [UIImage imageNamed:@"cash_sel"];
                self.sel = i;
            }];
        }
        
        NSArray *payType = @[@{@"img":@"icon_alipay",@"name":@"支付宝支付",@"color":AliPayColor},@{@"img":@"icon_wxpay",@"name":@"微信支付",@"color":WXPayColor}];
        __block NSInteger pay = 0;
        for (int i = 0; i < payType.count; i ++) {
            UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(_infoView.width+20+i*(_infoView.width-195), subTitle.maxY+77, 155, 76)];
            [button.layer setBorderWidth:2];
            if (i==pay) {
                [button.layer setBorderColor:((UIColor *)payType[i][@"color"]).CGColor];
            }else{
                [button.layer setBorderColor:[UIColor clearColor].CGColor];
            }
            button.layer.masksToBounds = YES;
            [button.layer setCornerRadius:18];
            button.tag = 200+i;
            button.backgroundColor = [((UIColor *)payType[i][@"color"]) colorWithAlphaComponent:0.08];
            [_infoView addSubview:button];
            [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                pay = i;
                if (i==0) {
                    [button.layer setBorderColor:((UIColor *)payType[i][@"color"]).CGColor];
                    [[self viewWithTag:201].layer setBorderColor:[UIColor clearColor].CGColor];
                }else{
                    [button.layer setBorderColor:((UIColor *)payType[i][@"color"]).CGColor];
                    [[self viewWithTag:200].layer setBorderColor:[UIColor clearColor].CGColor];
                }
            }];
            
            UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake((button.width-24)/2, 12, 24, 24)];
            img.image = [UIImage imageNamed:payType[i][@"img"]];
            [button addSubview:img];
            
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, img.maxY+10, button.width, 22)];
            label.text = payType[i][@"name"];
            label.font = MEDIUM_FONT(14);
            label.textColor = RealBlackColor;
            label.textAlignment = NSTextAlignmentCenter;
            [button addSubview:label];
        }
        
        UIButton *buy = [[UIButton alloc] initWithFrame:CGRectMake(20, subTitle.maxY+175, _infoView.width-40, 60)];
        [buy setBackgroundImage:[UIImage imageNamed:@"pay"] forState:UIControlStateNormal];
        [buy setBackgroundImage:[UIImage imageNamed:@"pay_high"] forState:UIControlStateHighlighted];
        [_infoView addSubview:buy];
        [[buy rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            if ([XDXShareInstance shareInstance].applePay) {
                NSArray *product = @[cashArray[self.sel][@"productId"]];
                NSLog(@"请求的产品%@",product);
                NSSet *nsset = [NSSet setWithArray:product];
                SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:nsset];
                request.delegate = self;
                [request start];
            }else{
                if ([self viewWithTag:102].x==20) {
                    [UIView animateWithDuration:0.3 animations:^{
                        [self viewWithTag:101].x = -[self viewWithTag:101].width;
                        [self viewWithTag:102].x = -[self viewWithTag:102].width;
                        [self viewWithTag:200].x = 20;
                        [self viewWithTag:201].x = self.infoView.width-175;
                    }];
                }else{
                    NSMutableDictionary *param = [NSMutableDictionary dictionary];
                    [param setValue:cashArray[self.sel][@"id"] forKey:@"planId"];
                    [param setValue:groupInfo[@"id"] forKey:@"groupId"];
                    [param setValue:pay>0?@"WechatPay":@"AliPay" forKey:@"payType"];
                    CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
                    [manager encryptedPOST:@"/system/group/membership/order_gen"
                                parameters:param
                                   success:^(NSDictionary *responseObject) {
                        if ([responseObject[@"code"] integerValue]==200) {
                            if (pay>0) {
                                NSData *jsonData = [responseObject[@"msg"] dataUsingEncoding:NSUTF8StringEncoding];
                                NSError *error = nil;
                                if (jsonData) {
                                    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
                                    if (dic) {
                                        PayReq *req = [[PayReq alloc] init];
                                        req.partnerId = [NSString stringWithFormat:@"%@",dic[@"partnerId"]];
                                        req.prepayId = [NSString stringWithFormat:@"%@",dic[@"prepayId"]];
                                        req.nonceStr = [NSString stringWithFormat:@"%@",dic[@"nonceStr"]];
                                        req.timeStamp = [[NSString stringWithFormat:@"%@",dic[@"timeStamp"]] intValue];
                                        req.package = @"Sign=WXPay";
                                        req.sign = [NSString stringWithFormat:@"%@",dic[@"sign"]];
                                        [WXApi sendReq:req completion:nil];
                                    }
                                }
                            }else{
                                NSString *order_string = responseObject[@"msg"];
                                [[AlipaySDK defaultService] payOrder:order_string fromScheme:@"famliy.points.alipay" callback:^(NSDictionary *resultDic) {
                                    NSInteger status = [resultDic[@"resultStatus"] integerValue];
                                    if (status == 9000) {
                                        [[HCToast shareInstance] showToast:@"支付成功"];
                                    }
                                }];
                            }
                        }else{
                            [[HCToast shareInstance] showToast:[NSString stringWithFormat:@"%@",responseObject[@"msg"]]];
                        }
                    }
                    failure:^(NSError *aError) {
                        
                    }];
                }
            }
        }];
        
        UILabel *notice = [[UILabel alloc] initWithFrame:CGRectMake(20, buy.maxY+8, _infoView.width-40, 48)];
        notice.userInteractionEnabled = YES;
        notice.textColor = GraryLightColor;
        notice.font = DEFAULT_FONT(12);
        NSString *nottiString = @"购买即同意《会员服务协议》及《隐私政策》该项目在iPhone和iPad上均可使用，此活动由家人足迹提供，与Apple Inc.无关;";
        NSMutableAttributedString *nottistr = [[NSMutableAttributedString alloc] initWithString:nottiString];
        [nottistr addAttribute:NSForegroundColorAttributeName value:NormalMainColor range:[nottiString rangeOfString:@"《会员服务协议》"]];
        [nottistr addAttribute:NSForegroundColorAttributeName value:NormalMainColor range:[nottiString rangeOfString:@"《隐私政策》"]];
        notice.numberOfLines = 2;
        notice.attributedText = nottistr;
        [_infoView addSubview:notice];
        
        UIButton *agree = [[UIButton alloc] initWithFrame:CGRectMake(60, 0, 96, 24)];
        [notice addSubview:agree];
        [[agree rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            if (self.CashViewBlock) {
                self.CashViewBlock(0);
            }
        }];
        
        UIButton *plicy = [[UIButton alloc] initWithFrame:CGRectMake(agree.maxX+12, 0, 72, 24)];
        [notice addSubview:plicy];
        [[plicy rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            if (self.CashViewBlock) {
                self.CashViewBlock(1);
            }
        }];
        
        UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        [self insertSubview:bgView atIndex:0];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
        [[tap rac_gestureSignal] subscribeNext:^(id x) {
            [self close];
        }];
        [bgView addGestureRecognizer:tap];
        
        [UIView animateWithDuration:0.3 animations:^{
            self.infoView.y = SCREEN_HEIGHT-self.infoView.height-32;
            self.backgroundColor = [RealBlackColor colorWithAlphaComponent:0.4];
        }];
        
    }
    return self;
}

- (void)close
{
    [UIView animateWithDuration:0.3 animations:^{
        self.infoView.y = SCREEN_HEIGHT;
        self.backgroundColor = [RealBlackColor colorWithAlphaComponent:0];
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }];
}

- (void)initSuccessView
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(12, SCREEN_HEIGHT, SCREEN_WIDTH-24, 365)];
    view.backgroundColor = RealWhiteColor;
    view.layer.masksToBounds = YES;
    [view.layer setCornerRadius:40];
    [self addSubview:view];
    
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0, 40, view.width, 28)];
    title.textAlignment = NSTextAlignmentCenter;
    title.text = @"恭喜呀！";
    title.textColor = RealBlackColor;
    title.font = MEDIUM_FONT(20);
    [view addSubview:title];
    
    UILabel *subTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, title.maxY+6, view.width, 24)];
    subTitle.textAlignment = NSTextAlignmentCenter;
    subTitle.text = @"家庭会员已开通! 感谢你的支持";
    subTitle.textColor = GraryLightColor;
    subTitle.font = DEFAULT_FONT(14);
    [view addSubview:subTitle];
    
    UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake((view.width-192)/2, subTitle.maxY+28, 192, 127)];
    img.image = [UIImage imageNamed:@"pay_success"];
    [view addSubview:img];
    
    UIButton *close = [[UIButton alloc] initWithFrame:CGRectMake(_infoView.width-46, 16, 30, 30)];
    [close setImage:[UIImage imageNamed:@"map_close"] forState:UIControlStateNormal];
    [view addSubview:close];
    [[close rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [UIView animateWithDuration:0.3 animations:^{
            view.y = SCREEN_HEIGHT;
            self.backgroundColor = [RealBlackColor colorWithAlphaComponent:0];
        } completion:^(BOOL finished) {
            [self removeFromSuperview];
            [[NSNotificationCenter defaultCenter] removeObserver:self];
        }];
    }];
    
    UIButton *done = [[UIButton alloc] initWithFrame:CGRectMake(20, img.maxY+28, view.width-40, 54)];
    done.backgroundColor = [NormalMainColor colorWithAlphaComponent:0.1];
    done.layer.masksToBounds = YES;
    [done.layer setCornerRadius:20];
    [done setTitle:@"好的" forState:UIControlStateNormal];
    [done setTitleColor:NormalMainColor forState:UIControlStateNormal];
    [done.titleLabel setFont:REAL_MEDIUM_FONT(15)];
    [view addSubview:done];
    [[done rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [UIView animateWithDuration:0.3 animations:^{
            view.y = SCREEN_HEIGHT;
            self.backgroundColor = [RealBlackColor colorWithAlphaComponent:0];
        } completion:^(BOOL finished) {
            [self removeFromSuperview];
            [[NSNotificationCenter defaultCenter] removeObserver:self];
        }];
    }];
    
    [UIView animateWithDuration:0.3 animations:^{
        view.y = SCREEN_HEIGHT-397;
    }];
}

- (void)PaySuccess
{
    [UIView animateWithDuration:0.3 animations:^{
        self.infoView.y = SCREEN_HEIGHT;
    } completion:^(BOOL finished) {
        [XDXShareInstance shareInstance].ReloadGroupListFlag = YES;
        [self initSuccessView];
    }];
}

#pragma mark - SKProductsRequestDelegate
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
    NSLog(@"-----------收到产品反馈信息--------------");
    NSArray *myProduct = response.products;
    NSLog(@"产品Product ID:%@",response.invalidProductIdentifiers);
    NSLog(@"产品付费数量: %d", (int)[myProduct count]);

    for(SKProduct *product in myProduct){
        SKMutablePayment *payment = nil;
        payment = [SKMutablePayment paymentWithProduct:product];
        [[SKPaymentQueue defaultQueue] addPayment:payment];
    }
}

- (void)request:(SKRequest *)request didFailWithError:(NSError *)error
{
    NSLog(@"------------------错误-----------------:%@", error);
    
}

- (void)requestDidFinish:(SKRequest *)request
{
    NSLog(@"------------反馈信息结束-----------------");
    
}


//监听购买结果的回调
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transaction
{
    SKPaymentTransaction *tran = transaction.lastObject;
    switch(tran.transactionState) {
            
        case SKPaymentTransactionStatePurchased:{
            NSLog(@"交易完成");
            NSURL *recepitURL = [[NSBundle mainBundle] appStoreReceiptURL];
            NSData *receipt = [NSData dataWithContentsOfURL:recepitURL];
            NSString *Receipt_data = [receipt base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
            
            
            [self PaySuccess];
            [[SKPaymentQueue defaultQueue] finishTransaction:tran];
            
            break;
        }
            
        case SKPaymentTransactionStatePurchasing:{
            NSLog(@"商品添加进列表");
            break;
        }
            
        case SKPaymentTransactionStateRestored:{
            NSLog(@"已经购买过商品");
            [[SKPaymentQueue defaultQueue] finishTransaction:tran];
            break;
        }
            
        case SKPaymentTransactionStateFailed:{
            NSLog(@"交易失败");
            [[SKPaymentQueue defaultQueue] finishTransaction:tran];
            
            break;
        }
            
        default:
            break;
            
    }
}

@end
